-- UIExploreTriggerInfo
-- Created by chendh
-- 探索触发事件信息界面

UIExploreTriggerInfo = class("UIExploreTriggerInfo", function()
    return cc.Layer:create();
end);

function UIExploreTriggerInfo.create(exploreIndex)
    return UIExploreTriggerInfo.new(exploreIndex);
end

local MAX_OPTION_NUM    = 3;

-- 构造函数
function UIExploreTriggerInfo:ctor(exploreIndex)
    self:setName("UIExploreTriggerInfo");
    local node = cc.CSLoader:createNode("layout/sky_city/ExploreTriggerInfo.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.BONUS_NOTIFY_ZORDER + 1);

    self.exploreIndex = exploreIndex;
    local skyExplore = ME.user.dbase:query("sky_explore", {});
    self.exploreInfo = skyExplore[exploreIndex];
    self.pos = self.exploreInfo.pos;
    self.triggerId = self.exploreInfo.trigger_id;
    self.questionId = self.exploreInfo.question_id;

    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 事件响应
function UIExploreTriggerInfo:registerEventCallback()
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIExploreTriggerInfo 界面析构清理");
            EventMgr.removeAll("UIExploreTriggerInfo");
        end
    end);
end

-- 重绘
function UIExploreTriggerInfo:redraw()
    local eventConfig = SkyExploreTriggerM.query(self.triggerId);

    local title, desc;

    if self.questionId then
        local questionConfig;
        questionConfig = SkyExploreTriggerM.queryQuestion(self.questionId);
        title = eventConfig["name"];
        desc = questionConfig["question"];
    else
        title = eventConfig["name"];
        desc = getLocStr(eventConfig["desc"]);

        -- 飞艇残骸的话要加上飞艇的名称
        if SkyExploreTriggerM.query(self.triggerId, "rule") == "ship_remains" then
            title = spliceLocStr(NewAirShipM.query(self.exploreInfo.ship_id, "name"), title);
        end

        local detail = eventConfig["detail"];
        -- 如果是字符串型的提示语配置，并且存在一样的公式时，认为是公式，调用公式获取
        if type(detail) == "string" and FormulaM.getFormula(detail) then
            detail = FormulaM.invoke(detail, self.triggerId, self.exploreInfo);
        end

        if string.len(detail) > 0 then
            desc = desc .. "\n[blue]" .. detail .. "[-]";
        end
    end

    -- 设置标题
    local titleLabel = findChildByName(self.node, "CT/title");
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(title);

    -- 正文样式
    local descLabel = findChildByName(self.node, "CT/desc");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    descLabel = applyString(descLabel, desc);

    -- 绘制选项按钮
    self:redrawOptions();

    -- 自适应所有组件
    local bg = findChildByName(self.node, "CT/bg_frame");
    local nodeArr = table.append({ titleLabel, descLabel }, self.optionList);
    local offsetArr = { 40, 40, };

    for _, _ in ipairs(self.optionList) do
        table.insert(offsetArr, -10);
    end

    AlignM.adaptLayout(bg, AlignM.BG_SIZE_NORMAL, nodeArr, offsetArr);

    -- 根据适配后的界面高度比例，对界面上的角标位置进行修正
    local bg1 = findChildByName(self.node, "CT/sub_bg_l");
    local bg2 = findChildByName(self.node, "CT/sub_bg_r");

    local fixY, deltaY = math.modf(AlignM.BG_SIZE_NORMAL.height * bg:getScaleY() / 2);
    fixY = fixY - 25 * bg:getScaleY();

    bg1:setPositionY(fixY);
    bg2:setPositionY(fixY);

    -- 背景的icon
    local iconImg = findChildByName(self.node, "CT/icon");
    -- 飞艇残骸的话要加上飞艇的名称
    if SkyExploreTriggerM.query(self.triggerId, "rule") == "ship_remains" then
        local icon = SkyShipSkillM.query(NewAirShipM.query(self.exploreInfo["ship_id"], "physic_skill"), "icon");
        iconImg:loadTexture(getAirShipSkillIconPath(icon));
    else
        iconImg:loadTexture(getTriggerIconPath(eventConfig["icon"]));
    end

    local scale = 1.5;

    if SkyExploreTriggerM.query(self.triggerId, "rule") == "remains" then
        scale = 1.2;
    end

    iconImg:setScale(scale);
    iconImg:setOpacity(80);
    iconImg:setPositionY(descLabel:getPositionY());
end

-- 绘制选项按钮
function UIExploreTriggerInfo:redrawOptions()
    self.optionList = {};

    local options = SkyExploreTriggerM.query(self.triggerId, "options");

    if self.questionId then
        options = SkyExploreTriggerM.queryQuestion(self.questionId, "options");
    end

    if SkyExploreTriggerM.query(self.triggerId, "rule") == "ship_remains" then
        -- 如果是飞艇残骸，那么隐藏最后一个选项不显示
        -- 因为默认最后一个选项为"调查"，而飞艇残骸只有在飞艇不一致，无法调查的时候才显示这个界面
        options = table.copy(options);
        table.remove(options, #options);
    end

    local optionBtn = findChildByName(self.node, "CT/option1");
    -- 根据配置，添加选项按钮
    for index, optionId in ipairs(options) do
        local button;
        if index == 1 then
            -- 第一个直接使用原先的option1
            button = optionBtn;
        else
            -- 其他的需要自己复制一个按钮出来
            button = optionBtn:clone();

            optionBtn:getParent():addChild(button);
        end

        -- 记录按钮的index和optionId
        button.index = index;
        button.optionId = optionId;

        -- 加入选项列表
        table.insert(self.optionList, button);

        -- 设置选项的文本
        TextStyleM.setTextStyle(button, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);

        if self.questionId then
            button.optionId = index;
            button:setTitleText(optionId);
        else
            local text = SkyExploreTriggerM.queryOption(optionId, "option");
            button:setTitleText(text);
        end
        -- 注册点击事件
        local function onButtonClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_return");

                -- 调用点击处理
                self:onClickOption(sender);
            end
        end
        button:addTouchEventListener(onButtonClick);
    end
end

-- 弹出失败提示语
function UIExploreTriggerInfo:doFailTip(optionId, reason)
    local tips;
    local failTip = SkyExploreTriggerM.queryOption(optionId, "fail_tip") or {};

    failTip = failTip[reason];
    -- 如果是字符串型的提示语配置，并且存在一样的公式时，认为是公式，调用公式获取提示语
    if type(failTip) == "string" and FormulaM.getFormula(failTip) then
        tips = FormulaM.invoke(failTip, self.triggerId, optionId, self.questionId);
    else
        tips = failTip;
    end

    if type(self.questionId) == "number" then
        tips = SkyExploreTriggerM.queryQuestion(self.questionId, "fail_tip");
        tips = getLocStr(tips);
    end

    if type(tips) == "string" then
        alert(tips);
    elseif type(tips) == "table" then
        for _, tipStr in ipairs(tips) do
            alert(tipStr);
        end
    end
end

-- 选择了选项
function UIExploreTriggerInfo:doChoiceOption(optionId)
    local cost = self.exploreInfo["cost"];

    if type(cost) == "table" and type(cost[optionId]) == "table" then
        for _, arr in ipairs(cost[optionId]) do
            if arr[1] == 1 then
                -- 道具
                if ItemM.getAmount(ME.user, arr[2]) < arr[3] then
                    self:doFailTip(optionId, "cost");
                    return;
                end
            elseif arr[1] == 2 then
                -- 属性
                if ME.user.dbase:query(arr[2], 0) < arr[3] then
                    self:doFailTip(optionId, "cost");
                    return;
                end
            end
        end
    end

    -- 去服务器执行选择操作
    SkyExploreTriggerM.choiceOption(self.exploreIndex, optionId, self.extraData or {});

    -- 关闭 选项 界面
    UIMgr.getCurrentScene():removeFormByName("UIExploreTriggerInfo");
end

-- 选项点击回调
function UIExploreTriggerInfo:onClickOption(button)
    local optionId;
    optionId = button.optionId;

    local optionInfo = SkyExploreTriggerM.queryOption(optionId);
    local extraData = optionInfo["extra_data"];

    local function combatTip()
        -- 即将开始战斗
        confirm2(CONFIRM_TYPE_OK_NOBACK, SkyExploreTriggerM.query(self.triggerId, "name"), extraData["combat_desc"],
            function ()
                self:doChoiceOption(optionId);
            end, nil, getLocStr("enter_combat"));
    end

    if extraData["rule"] == "explore_shop" then
        -- 打开天空触发特殊商店界面
        require "game/ui/form/sky_city/UISkyCityExploreShop"
        local uiForm = UISkyCityExploreShop.create(self.exploreIndex);
        UIMgr.getCurrentScene():addForm(uiForm);

        UIMgr.getCurrentScene():removeFormByName("UIExploreTriggerInfo");
    elseif extraData["rule"] == "active_ship" or extraData["rule"] == "own_ship" then
        -- 去更换出战飞艇
        -- 这里直接关闭界面，让玩家自己去更换飞艇
        UIMgr.getCurrentScene():removeFormByName("UIExploreTriggerInfo");
    elseif extraData["rule"] == "combat" then
        -- 即将开始战斗
        combatTip();
    elseif extraData["rule"] == "explore_level_combat1" and
        ME.user.dbase:query("explore_level", 0) < extraData["explore_level"] then
            combatTip();
    elseif extraData["rule"] == "explore_level_combat2" and
        ME.user.dbase:query("explore_level", 0) >= extraData["explore_level"] then
        -- 即将开始战斗
        combatTip();
    elseif extraData["rule"] == "explore_level_limit" then
        -- 要求探索等级超过一定的级别才能选择
        local value = extraData["value"];

        if value > ME.user.dbase:query("explore_level", 0) then
            -- 探索等级不足，弹出提示
            self:doFailTip(optionId, "explore_level");
        else
            -- 探索等级满足，执行选项
            self:doChoiceOption(optionId);
        end

        UIMgr.getCurrentScene():removeFormByName("UIExploreTriggerInfo");
    elseif extraData["rule"] == "random_combat" then
        -- 概率触发战斗
        local value = extraData["value"];
        local optionResultId = randomSelectBySeed(value, math.random(1000));
        self.extraData = {["option_result_id"] = optionResultId,};

        if optionResultId == 1 then
            -- 即将开始战斗
            combatTip();
        else
            -- 直接执行选项
            self:doChoiceOption(optionId);
        end
    else
        -- 直接执行选项
        self:doChoiceOption(optionId);
    end
end

-- 注册点击事件
function UIExploreTriggerInfo:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");

            UIMgr.getCurrentScene():removeFormByName("UIExploreTriggerInfo");
        end
    end
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
    AddBackEventHandler(self, btnBack, onBackClick);

    -- 黑色背景点击响应
    local bgNode = findChildByName(self.node, "bg/bgImg");
    bgNode:setTouchEnabled(true);
    bgNode:addTouchEventListener(onBackClick);
end

-- 适配
function UIExploreTriggerInfo:resize()
    local node = self.node;

    -- bg充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

